//
//  XJ_RegiertUserdViewController.m
//  XunJieProject
//
//  Created by 薛子 on 2018/6/7.
//  Copyright © 2018年 Soowin. All rights reserved.
//

#import "XJ_RegiertUserdViewController.h"
#import "TregularexpressionNSObjec.h"
#import "XJ_ApplicationDetailViewController.h"
#import "WCQRCodeScanningVC.h"
@interface XJ_RegiertUserdViewController ()


@property (weak, nonatomic) IBOutlet UIView *phoneView;

@property (weak, nonatomic) IBOutlet UIView *codeView;

@property (weak, nonatomic) IBOutlet UIView *passwordView;

@property (weak, nonatomic) IBOutlet UIView *yqCodeView;
@property (weak, nonatomic) IBOutlet UIButton *regiterUserdButton;
@property (weak, nonatomic) IBOutlet UIButton *codeButton;
@property (weak, nonatomic) IBOutlet UITextField *phoneTxt;
@property (weak, nonatomic) IBOutlet UITextField *codeTxt;
@property (weak, nonatomic) IBOutlet UITextField *passwordTxt;
@property (weak, nonatomic) IBOutlet UITextField *yqCodeTxt;
@property (weak, nonatomic) IBOutlet UIView *picView;
@property (weak, nonatomic) IBOutlet UITextField *picTxt;
@property (weak, nonatomic) IBOutlet UIButton *picButton;
@property (weak, nonatomic) IBOutlet UIImageView *picImage;

@end

@implementation XJ_RegiertUserdViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.nav_btmView.backgroundColor = [UIColor clearColor];
    self.nav_titleLabel.text = @"注册";
    [self.nav_backButton setImage:[UIImage imageNamed:@"close_btn"] forState:UIControlStateNormal];
//    self.nav_backButton.frame = CGRectMake(20,30, 20, 20);
    
    
    [self getPictureCode];
    
    
    _phoneView.layer.cornerRadius = 4;
    _phoneView.layer.borderWidth = 1.5;
    _phoneView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _phoneTxt.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneTxt addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    _picView.layer.cornerRadius = 4;
    _picView.layer.borderWidth = 1.5;
    _picView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _picTxt.keyboardType = UIKeyboardTypeNumberPad;
    
    _codeView.layer.cornerRadius = 4;
    _codeView.layer.borderWidth = 1.5;
    _codeView.layer.borderColor  = [UIColor whiteColor].CGColor;
    _codeTxt.keyboardType = UIKeyboardTypeNumberPad;
    
    _passwordView.layer.cornerRadius = 4;
    _passwordView.layer.borderWidth = 1.5;
    _passwordView.layer.borderColor  = [UIColor whiteColor].CGColor;
    
    _yqCodeView.layer.cornerRadius = 4;
    _yqCodeView.layer.borderWidth = 1.5;
    _yqCodeView.layer.borderColor  = [UIColor whiteColor].CGColor;
    
    
    _codeButton.layer.cornerRadius = 4;
    _regiterUserdButton.layer.cornerRadius = 4;
    
    NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"手机号码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_phoneTxt.font
                                        }];
    _phoneTxt.attributedPlaceholder = attrString;
    
    NSAttributedString *attrString2 = [[NSAttributedString alloc] initWithString:@"验证码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_codeTxt.font
                                        }];
    _codeTxt.attributedPlaceholder = attrString2;
    
    NSAttributedString *attrString3 = [[NSAttributedString alloc] initWithString:@"设置密码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_passwordTxt.font
                                        }];
    _passwordTxt.attributedPlaceholder = attrString3;
    
    NSAttributedString *attrString4 = [[NSAttributedString alloc] initWithString:@"激活码" attributes:
                                      @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                        NSFontAttributeName:_yqCodeTxt.font
                                        }];
    _yqCodeTxt.attributedPlaceholder = attrString4;
    
    NSAttributedString *attrString5 = [[NSAttributedString alloc] initWithString:@"图片验证码" attributes:
                                       @{NSForegroundColorAttributeName:[UIColor whiteColor],
                                         NSFontAttributeName:_picTxt.font
                                         }];
    _picTxt.attributedPlaceholder = attrString5;
    
    // Do any additional setup after loading the view from its nib.
}

- (IBAction)registerProtocal:(id)sender {
    
    XJ_ApplicationDetailViewController * VC = [[XJ_ApplicationDetailViewController alloc]init];
    VC.isProtocal = YES;
    [self.navigationController pushViewController:VC animated:YES];
   
    
}
- (IBAction)registerUserd:(id)sender {
    
    if (_phoneTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    if (![TregularexpressionNSObjec isMobileNumber:_phoneTxt.text]) {
        
        [XJ_Utils alertViewWithMessage:@"请输入正确手机号"];
        return;
    }
    
    if (_codeTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入验证码"];
        return;
    }
    
    if (_passwordTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入密码"];
        return;
    }
    if (_yqCodeTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入邀请码"];
        return;
    }
    
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:_yqCodeTxt.text forKey:@"inviteCode"];
//    [dic setValue:[[_passwordTxt.text md5HexDigest] uppercaseString]forKey:@"password"];
    [dic setValue:_passwordTxt.text forKey:@"password"];
    [dic setValue:_phoneTxt.text forKey:@"mobile"];
    [dic setValue:_codeTxt.text forKey:@"verifyCode"];
    [dic setValue:@"1" forKey:@"protocolFlag"];
//    [dic setValue:_yqCodeTxt.text forKey:@"registrationId"];
    
    [XJ_Utils post:@"user/register?" parameters:dic success:^(NSInteger recode, id jsonObject) {
        
        ZDXAlertView *alext =[[ZDXAlertView alloc]initWithMessage:@"注册成功，请登录" image:@"pop_msg_succeed_xs"];
        [alext showXLAlertView];
        [self.navigationController popViewControllerAnimated:YES];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
    }];
    
}

- (IBAction)getCode:(id)sender {
    
    if (_phoneTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入手机号"];
        return;
    }
    
    if (![TregularexpressionNSObjec isMobileNumber:_phoneTxt.text]) {
        
        [XJ_Utils alertViewWithMessage:@"请输入正确手机号"];
        return;
    }
    
    if (_picTxt.text.length == 0) {
        
        [XJ_Utils alertViewWithMessage:@"请输入图片验证码"];
        return;
    }

    NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSLog(@"设备唯一标识符:%@",identifierStr);
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:identifierStr forKey:@"equipmentNo"];
    [dic setValue:@(1)forKey:@"verifyCodeType"];
    [dic setValue:_phoneTxt.text forKey:@"mobile"];
    [dic setValue:_picTxt.text forKey:@"identifyCode"];
    
    [XJ_Utils post:@"user/beforeSendVerify?" parameters:dic success:^(NSInteger recode, id jsonObject) {

        [XJ_Utils alertViewWithMessage:@"验证码发送成功"];
        [self startAnimation];

    } failure:^(NSInteger recode, NSError *error) {
        [XJ_Utils alertViewWithMessage:@"验证码发送失败"];

    }];
}

//更新图片验证码
- (IBAction)getPicCode:(id)sender {
    
    [self getPictureCode];
}

- (IBAction)scanYQCode:(id)sender {
    
    
    WCQRCodeScanningVC *WCVC = [[WCQRCodeScanningVC alloc] init];
    [self QRCodeScanVC:WCVC];
    
}

- (void)QRCodeScanVC:(UIViewController *)scanVC {
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    if (device) {
        AVAuthorizationStatus status = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
        switch (status) {
            case AVAuthorizationStatusNotDetermined: {
                [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
                    if (granted) {
                        dispatch_sync(dispatch_get_main_queue(), ^{
                            [self.navigationController pushViewController:scanVC animated:YES];
                        });
                        NSLog(@"用户第一次同意了访问相机权限 - - %@", [NSThread currentThread]);
                    } else {
                        NSLog(@"用户第一次拒绝了访问相机权限 - - %@", [NSThread currentThread]);
                    }
                }];
                break;
            }
            case AVAuthorizationStatusAuthorized: {
                [self.navigationController pushViewController:scanVC animated:YES];
                break;
            }
            case AVAuthorizationStatusDenied: {
                UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"请去-> [设置 - 隐私 - 相机 - SGQRCodeExample] 打开访问开关" preferredStyle:(UIAlertControllerStyleAlert)];
                UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                    
                }];
                
                [alertC addAction:alertA];
                [self presentViewController:alertC animated:YES completion:nil];
                break;
            }
            case AVAuthorizationStatusRestricted: {
                NSLog(@"因为系统原因, 无法访问相册");
                break;
            }
                
            default:
                break;
        }
        return;
    }
    
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"未检测到您的摄像头" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *alertA = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertC addAction:alertA];
    [self presentViewController:alertC animated:YES completion:nil];
}


//获取图片验证码
- (void)getPictureCode{
    
    NSString *identifierStr = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSLog(@"设备唯一标识符:%@",identifierStr);
    
    NSMutableDictionary * dic = [NSMutableDictionary dictionary];
    [dic setValue:identifierStr forKey:@"equipmentNo"];
    [dic setValue:@(1)forKey:@"verifyCodeType"];
    
    NSString * urlStr = [NSString stringWithFormat:@"%@user/getPicCode?equipmentNo=%@&verifyCodeType=1",HOSTURL,identifierStr];
    [[SDImageCache sharedImageCache] clearDiskOnCompletion:nil];
    [[SDImageCache sharedImageCache] clearMemory];
    [_picImage sd_setImageWithURL:[NSURL URLWithString:urlStr] placeholderImage:[UIImage imageNamed:@"img_no_image"]];
}

- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == self.phoneTxt) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }
    
}

- (void)startAnimation
{
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
            
                [self->_codeButton setTitle:[NSString stringWithFormat:@"获取验证码"] forState:UIControlStateNormal];
                [self->_codeButton setBackgroundColor:[UIColor orangeColor]];
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果
                [self->_codeButton setTitle:[NSString stringWithFormat:@"剩余%d秒",seconds] forState:UIControlStateNormal];
                [self->_codeButton setBackgroundColor:[UIColor lightGrayColor]];
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
